<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 显示主要页面的板块 -->
    <el-card class="box-card">
      <!-- 网格布局 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户页面主要内容 -->
      <!-- :data是接收数组的数据 -->
      <el-table :data="userlist" style="width: 100%">
        <!-- label是标题 prop是指从数据中过来的参数-->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作地方 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- sise 是按钮大小 编辑按钮-->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="aditHandle(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeUser(scope.row.id)"
            ></el-button>
            <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="setRoleUserList(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页地方 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="handleAddDialogClose"
    >
      <span>
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑栏 -->
    <el-dialog
      title="修改"
      :visible.sync="aditDialogVisible"
      width="50%"
      @closed="handleAditDialogClose"
    >
      <span>
        <el-form :model="aditForm" :rules="aditFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="aditForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="aditForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="aditForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="aditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="aditUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限对话框 -->
    <el-dialog title="修改" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <span>
        <p>当前的用户名: {{userRoleList.username}}</p>
        <p>当前的角色: {{userRoleList.role_name}}</p>
        <p>
          当前的角色
          <el-select v-model="selectRoleValue" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1, //  这是请求页码
        pagesize: 2 // 请求条数
      },
      userlist: [],
      total: 0,
      // 添加对话框
      addDialogVisible: false,
      // 编辑对话框
      aditDialogVisible: false,
      // 权限对话框
      setRoleDialogVisible: false,

      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 权限列表
      userRoleList: [],
      // 获取列表
      rolesList: [],
      selectRoleValue: '',
      // 对话框
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur'
          }
        ]
      },
      // 编辑
      // 添加用户的表单数据
      aditForm: {},
      // 添加表单的验证规则对象
      aditFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur'
          }
        ]
      },
      // 保存id
      aditId: ''
    }
  },
  created () {
    // 调用函数数据
    this.getUserList()
  },
  methods: {
    // 获取用户数据
    async getUserList () {
      const { data: isUserList } = await this.$http.get('users', {
        params: this.queryInfo
      })
      this.userlist = isUserList.data.users
      this.total = isUserList.data.total
    },
    handleSizeChange (page) {
      this.queryInfo.pagesize = page
      // 调用函数数据
      this.getUserList()
    },
    handleCurrentChange (num) {
      this.queryInfo.pagenum = num
      // 调用函数数据
      this.getUserList()
    },
    async userChange (info) {
      await this.$http.put(`users/${info.id}/state/${info.mg_state}`)
      this.$message({
        message: '修改成功',
        type: 'success'
      })
    },
    handleAddDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addFormRef.validate(async (isValid) => {
        if (!isValid) return
        // console.log()
        // 发送请求
        const { data: res } = await this.$http.post('users', this.addForm)
        // 验证失败
        if (res.meta.status !== 201) {
          this.$message({
            message: res.meta.msg,
            type: 'error',
            showColse: true
          })
        } else {
          // 验证成功
          this.$message({
            message: '创建用户成功',
            type: 'success',
            showColse: true
          })
          // 关闭对话框
          this.addDialogVisible = false
          // 重新加载数据
          this.getUserList()
        }
      })
    },
    // 编辑确定按钮
    async aditUser () {
      console.log(this.aditId)
      this.$refs.aditFormRules.validate(async (isvalue) => {
        if (!isvalue) return
        const { data: res } = await this.$http.put(
          'users/' + this.aditId,
          // email: this.aditForm.email, username: this.aditForm.username
          this.aditForm
        )
        console.log(res)
        if (res.meta.status !== 200) return this.$message('失败')
        this.$message('成功')
        this.getUserList()
        this.aditDialogVisible = false
      })
    },
    handleAditDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 根据id查询
    async aditHandle (id) {
      const { data: res } = await this.$http.get('users/' + id)
      this.aditForm = res.data
      // console.log(id)
      this.aditDialogVisible = true
      this.aditId = res.data.id
    },
    removeUser (id) {
      // 代码片段 elmecon
      this.$confirm('确定删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success',
        callback: async (action) => {
          if (action === 'confirm') {
            await this.$http.delete('users/' + id)
            this.$message('删除成功')
          }
          this.getUserList()
        }
      })
    },
    // 权限
    async setRoleUserList (userinfo) {
      this.userRoleList = userinfo
      const { data: res } = await this.$http.get('roles')
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    async setUserDialog () {
      await this.$http.put(`users/${this.userRoleList.id}/role`, { rid: this.selectRoleValue })
      // console.log(res)
      if (!this.selectRoleValue) {
        return this.$message.error('请选择需要分配的角色')
      }
      this.$message({
        message: '分配成功',
        type: 'success',
        showColse: true
      })
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    setRoleDialogClosed () {
      // 当关闭对话框的时候，重置下拉框中的内容
      this.selectRoleValue = ''
      this.rolesList = {}
    }
  }
}
</script>
<style lang="less" scoped>
</style>
